<template>
<div class="login-header">
    <div class="header-main" style="width: 100%; padding: 0px 20px;">
      <div class="logo"><span><img src="/src/assets/logo.png" alt="" class="img-logo"></span> <span
          class="line-v">|</span> <span class="text">欢迎登录</span></div>
      
    </div>
  </div>
  <div class="login-container">
    <a-row>
      <a-col :xs="0" :md="0" :sm="12" :lg="14" :xl="16"></a-col>
      <a-col :xs="24" :sm="24" :md="12" :lg="10" :xl="6">
        <div class="login-container-form">
          <div class="login-container-hello">您好!</div>
          <div class="login-container-title">欢迎登录中药材交易平台</div>
          <a-form ref="formRef" :model="form" :rules="rules" @keyup.enter="handleSubmit">
            <a-form-item name="username">
              <a-input v-model:value="form.username" autocomplete="off" placeholder="请输入账号" size="large">
                <template v-slot:prefix>
                  <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item name="password">
             <a-input-password v-model:value="form.password" autocomplete="off" placeholder="请输入密码" size="large">
                <template v-slot:prefix>
                  <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item name="code">
              <a-input-group compact>
                <a-input v-model:value="form.code" :maxlength="6" placeholder="请输入验证码" size="large" style="width: calc(100% - 100px)" />
                <a-image :width="100" :height="40" :preview="false" :src="captchaImage" @click="refreshCaptcha" alt="验证码" />
             </a-input-group>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" :block=true size="large" @click="handleSubmit()">
                登录
              </a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-col>
    </a-row>
  </div>
  <div class="login-footer"
    style="background: rgb(255, 255, 255); position: absolute; left: 0px; right: 0px; bottom: 0px; font-size: 14px;">
    <span> Copyright @ 2022 - 2024 XXXX有限公司 版权所有</span>
    <a href="https://beian.miit.gov.cn/" target="_blank"><span class="footer-r" style="margin-left: 15px;cursor: pointer;">鲁ICP备2021033292号-2</span></a>
  </div>
</template>

<script>
import store from '@/store'; 
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'

import { defineComponent, onMounted, reactive, ref } from "vue"
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'

import { encryptPassword } from '@/utils/utils'
import qs from 'qs'
import request from '@/utils/request'

export default defineComponent({
  name: "login",
  components: {
    UserOutlined,
    LockOutlined
  },
  setup() {
    onMounted(async() => {
      refreshCaptcha();
    });

    // 表单数据
    const form = data_form()

    const rules = reactive({
      username: [
        {
          required: true,
          message: '请输入账号',
          trigger: 'change'
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'change'
        }
      ],
      code: [
        {
          required: true,
          message: '请输入验证码',
          trigger: 'change'
        }
      ]
    })

    const formRef = ref()

    const captchaImage = ref('')

    const router = useRouter()

    const refreshCaptcha = async () => {
      try {
        const timestamp = new Date().getTime();
        // 将GET请求改为POST请求，解决405 Method Not Allowed错误
        const response = await request.get('/api/base/captcha/image', {
          t: timestamp
        });
        
        form.random = response.data.data.random;
        captchaImage.value = response.data.data.base64;
      } catch (error) {
        console.log(error);
        message.error('验证码获取失败，请重试');
      }
    }

    /**
     * @desc: 登录提交
     * @param 无
     */
    const handleSubmit = () => {
      formRef.value.validate().then(async () => {
        const response = await request.get('/api/upms/crypto/key');
        let encKey = response.data.data.key;
        let password = encryptPassword(encKey, form.password);
        let params = {
          username: form.username,
          password: password,
          code: form.code,
          random: form.random
        };
        const data = (await request.post('/api/base/auth/login/username', params)).data;
        if(data.code == 0){
          store.commit('user/SET_TOKEN', data.data.token);
          let user = (await request.get('/upms/profile/get')).data.data;
          store.commit('user/SET_USER', user);
          //判断是否有跳转地址
          const query = qs.parse(location.search.substring(1));
          if (query.backUrl) {
              let backUrl = decodeURIComponent(query.backUrl);
              window.location = backUrl + (backUrl.indexOf('?') >= 0 ? '&' : '?') + 'token=' + token;
          } else {
            router.push('/');
          }
        }else{
          refreshCaptcha();
          message.error(data.msg || '登录失败');
        }
      })
    }

    return { formRef, form, rules,captchaImage, handleSubmit,refreshCaptcha }

  },
});

function data_form () {
  const form = reactive({
    username: undefined,
    password: undefined,
    code: undefined,
    random: undefined
  })
  return form
}
</script>

<style lang="less" scoped>

.login-header {
  height: 80px;
  width: 100%;
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
}

.login-header .header-main {
  display: flex;
  display: -ms-flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
  width: 100%;
  height: 100%;
  padding: 0 20px;
}

.login-header .header-main .menus {
  margin-right: 20px;
  padding: 0 0 10px;
}

.login-header .header-main .menu {
  display: inline-block;
  padding: 0 16px;
  line-height: 1;
  cursor: pointer;
}

.login-header a, .login-header a:hover {
    color: #303133;
    text-decoration: none;
}

.login-header .header-main .menus .line-v {
    display: inline-block;
    width: 1px;
    height: 10px;
    background-color: rgba(0, 0, 0, 0.25);
}

.login-header .header-main .menu:hover {
  color: #015fc9;
}

.login-header .header-main .menus .menu.disabled {
    cursor: auto;
    color: inherit;
}

.login-header .header-main .logo {
  height: 55px;
  text-align: left;
  font-size: 20px;
  line-height: 55px;
}

.login-header .header-main .menus .highlight {
    color: #F8761A;
}

.login-header .header-main .logo .img-logo {
    height: 55px;
    vertical-align: top;
    cursor: pointer;
}

.login-header .header-main .logo .line-v {
    margin: 0 8px;
    color: #e7e7e7;
}

.login-footer {
  position: relative;
  z-index: 999;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  min-height: 48px;
  line-height: 48px;
  background: #fff;
  text-align: center;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

.login-footer a, .login-footer a:hover {
    color: rgba(0, 0, 0, 0.65);
    text-decoration: none;
}

.login-container {
  width: 100%;
  height: 100vh;
  background: url('/src/assets/login/login-bg.png');
  background-size: cover;
  overflow: hidden;
  & .login-container-form {
    width: calc(100% - 40px);
    height: 400px;
    padding: 4vh;
    margin-top: calc((100vh - 380px) / 2);
    margin-right: 20px;
    margin-left: 20px;
    background-color: #fff;
    background-size: 100% 100%;
    border-radius: 10px;
    box-shadow: 0 2px 8px 0 rgba(7, 17, 27, 0.06);
    & .login-container-hello {
      font-size: 32px;
      color: #303133
    }
    & .login-container-title {
      margin-bottom: 30px;
      font-size: 20px;
      color: #303133
    }
  }
  .login-container-tips {
    position: fixed;
    bottom: 10px;
    width: 100%;
    height: 40px;
    color: rgba(255, 255, 255, 0.856);
    text-align: center;
  }
}
</style>
